package com.linked.basemanage.permissioncontrol.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.basemanage.permissioncontrol.bean.param.AddPowersToRoleParam;
import com.linked.basemanage.permissioncontrol.bean.po.RolePowerPO;
import com.linked.basemanage.permissioncontrol.mapper.IRolePowerMapper;
import com.linked.basemanage.permissioncontrol.service.IRolePowersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :dbq
 * @date : 2023/2/22 15:52
 * @description : desc
 */
@Slf4j
@Service
public class RolePowersServiceImpl implements IRolePowersService {

    private final ObjectMapper mapper;

    private final IRolePowerMapper rolePowerMapper;

    private final TransactionTemplate transactionTemplate;

    @Autowired
    public RolePowersServiceImpl(ObjectMapper mapper, IRolePowerMapper rolePowerMapper, TransactionTemplate transactionTemplate) {
        this.mapper = mapper;
        this.rolePowerMapper = rolePowerMapper;
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public boolean addPowersToRole(AddPowersToRoleParam param) throws Exception {
        LocalDateTime dateTime = LocalDateTime.now();
        return transactionTemplate.execute(action -> {
            try {
                AtomicInteger saveCount = new AtomicInteger(0);
                param.getPowerIds().stream().forEach(powerId -> {
                    RolePowerPO temp = new RolePowerPO();
                    temp.setPowerId(powerId);
                    temp.setRoleId(param.getRoleId());
                    temp.setCreateUserId(param.getUpdateUserId());
                    temp.setUpdateUserId(param.getUpdateUserId());
                    temp.setUpdateTime(dateTime);
                    saveCount.addAndGet(rolePowerMapper.insert(temp));
                });
                if (param.getPowerIds().size() != saveCount.get()) {
                    log.info("给角色加权限，部分失败！");
                    action.setRollbackOnly();
                    return false;
                }
            } catch (Exception e) {
                log.error("给角色加权限异常！", e);
                action.setRollbackOnly();
                return false;
            }
            return true;
        });
    }
}
